import { asyncRouterMap, constantRouterMap } from '@/config/router.config'

/**
 * 过滤账户是否拥有某一个权限，并将菜单从加载列表移除
 *
 * @param permission
 * @param route
 * @returns {boolean}
 */
function hasPermission (authRouters, route) {
  if (route.name) {
    return authRouters.some(auth => route.name === auth)
  } else {
    return true
  }
}

/**
 * 单账户多角色时，使用该方法可过滤角色不存在的菜单
 *
 * @param roles
 * @param route
 * @returns {*}
 */
// eslint-disable-next-line
function hasRole(roles, route) {
  if (route.meta && route.meta.roles) {
    return route.meta.roles.includes(roles.id)
  } else {
    return true
  }
}

function filterAsyncRouter (routerMap, authRouters) {
  const res = []
  routerMap.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(authRouters, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRouter(tmp.children, authRouters)
      }
      res.push(tmp)
    }
  })
  return res
}

const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    }
  },
  actions: {
    GenerateRoutes ({ commit }, data) {
      return new Promise(resolve => {
        const { serverRouterMap } = data
        let accessedRouters = []
        let wholeAccessRouters = asyncRouterMap
        let routersMap = wholeAccessRouters[0].children
        
        if(serverRouterMap && routersMap) accessedRouters = filterAsyncRouter(routersMap, serverRouterMap)

        // const { roles } = data
        // const accessedRouters = filterAsyncRouter(asyncRouterMap, roles)
        wholeAccessRouters[0].children = accessedRouters
        
        commit('SET_ROUTERS', wholeAccessRouters)
        resolve(wholeAccessRouters)
      })
    }
  }
}

export default permission
